const express = require('express');
const { body, param, validationResult } = require('express-validator');
const Menu = require('../models/Menu');

const router = express.Router();

// 验证错误处理中间件
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '请求参数验证失败',
      errors: errors.array()
    });
  }
  next();
};

// 获取菜单树
router.get('/', async (req, res) => {
  try {
    const menus = await Menu.findAll();
    const tree = Menu.buildMenuTree(menus);
    res.json({ success: true, message: '获取菜单树成功', data: tree });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 获取权限树（菜单+按钮权限）
router.get('/permissions/tree', async (req, res) => {
  try {
    const menus = await Menu.findAll();
    // 只保留必要字段，兼容前端TreeSelect
    function mapTree(tree) {
      return tree.map(item => ({
        title: item.name + (item.permission ? `（${item.permission}）` : ''),
        value: item.permission || String(item.id),
        key: item.permission || String(item.id),
        children: item.children && item.children.length > 0 ? mapTree(item.children) : undefined,
        // 可根据需要添加其他字段
      }));
    }
    const tree = Menu.buildMenuTree(menus);
    const permissionTree = mapTree(tree);
    res.json({ success: true, data: permissionTree });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 创建菜单
router.post('/', [
  body('name').notEmpty(),
  body('parent_id').optional(),
  body('type').notEmpty(),
  body('order_num').isInt(),
  handleValidationErrors
], async (req, res) => {
  try {
    const menu = await Menu.create(req.body);
    res.status(201).json({ success: true, message: '创建菜单成功', data: menu });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 更新菜单
router.put('/:id', [
  param('id').isInt(),
  body('name').optional(),
  body('parent_id').optional(),
  body('type').optional(),
  body('order_num').optional().isInt(),
  handleValidationErrors
], async (req, res) => {
  try {
    const menu = await Menu.update(req.params.id, req.body);
    res.json({ success: true, message: '更新菜单成功', data: menu });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

// 删除菜单
router.delete('/:id', [
  param('id').isInt(),
  handleValidationErrors
], async (req, res) => {
  try {
    await Menu.delete(req.params.id);
    res.json({ success: true, message: '删除菜单成功' });
  } catch (error) {
    res.status(500).json({ success: false, message: error.message });
  }
});

module.exports = router; 